package com.bj58.heatmap.main;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.bj58.heatmap.db.HeatMapService;
import com.bj58.heatmap.model.HomeHeatMap_PC;
import com.bj58.heatmap.util.DDateUtils;
import com.bj58.heatmap.util.IOUtils;
import com.bj58.wf.log.Log;
import com.bj58.wf.log.LogFactory;

public class ChangeStyle_PC_Month {
	private static Log log = LogFactory.getLog(ChangeStyle_PC.class);
	private static HeatMapService service = new HeatMapService();
	
	private static String colorBar = "\n<div align=\"center\">\n"
		+ "<table height=\"35\">\n" + "<tr>\n"
		+ "<td style=\"width:10%\" bgcolor=\"#e1e1e1\"></td>\n"+
		"<td><font color='red'><#1#</font></td>\n"+
		"<td style=\"width:10%\" bgcolor=\"#ffd985\"></td>\n"+
		"<td><font color='red'><#2#</font></td>\n"+
		"<td style=\"width:10%\" bgcolor=\"#ffa037\"></td>\n"+
		"<td><font color='red'><#3#</font></td>\n"+
		"<td style=\"width:10%\" bgcolor=\"#ff5f3d\"></td>\n"+
		"<td><font color='red'><#4#</font></td>\n"+
		 "<td style=\"width:10%\" bgcolor=\"#be0100\"></td>\n"
		+ "</tr>\n" + "</table>\n" + "</div>\n";
	
	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		Calendar calendar = Calendar.getInstance();
		String folder="";
		if(args==null||args.length==0){
			calendar.add(Calendar.DATE, -1);
			folder = new SimpleDateFormat("yyyyMMdd").format(calendar.getTime());
		}
		else{
			folder=args[0];
			calendar.set(Calendar.YEAR, Integer.parseInt(folder.substring(0, 4)));
			calendar.set(Calendar.MONTH, Integer.parseInt(folder.substring(4, 6))-1);
			calendar.set(Calendar.DATE, Integer.parseInt(folder.substring(6, 8)));
		}
		
		String stat_date = DDateUtils.strToStr(folder, "yyyyMMdd", "yyyy-MM-dd");
		long maxWait = 5*60*60*1000; //最多等5个小时
		while(maxWait > 0){
			log.info("begin check source table :"+stat_date);
			int count = service.countAll(stat_date);
			if(count > 0){
				log.info("source table has "+count+" recodes!");
				break;
			}
			log.info("source table is not ready then sleep for 10 minites!");
			maxWait -= 10*60*1000;
			Thread.sleep(10*60*1000);
		}
		File savePath = new File(WebCrawler.getHtmlPath() + folder); //源文件路径
		File savePath_new = new File(WebCrawler.getHtmlPath_new() + folder);	//目标文件路径
		if (!savePath_new.exists())
			savePath_new.mkdirs();
		File[] files = savePath.listFiles();
		for (File f : files) {
			if (f.isFile()) {
				String html = IOUtils.readFile(f);
				String t="pkg/index/index_common_homepage";
				html=html.replaceAll(t, "");
				String filename = f.getName();
				if (filename.endsWith("_M.html")) //只处理PC端的
					continue;				
				html = changeStyle(html, calendar.getTime(),filename);
				IOUtils.saveFile(html, new File(savePath_new, "month_"+filename));
			}
		}
		System.out.println("ChangeStyle complete!");
		System.exit(0);
	}

	/**
	 * 更改静态页面
	 * @param html
	 * @return
	 */
	public static String changeStyle(String html, Date date, String filename) {
		String strDate = DDateUtils.dateToStr(date, "yyyy-MM-dd");
		String folder = DDateUtils.dateToStr(date, "yyyyMMdd");
//		String lastday = DDateUtils.varDate(strDate, "yyyy-MM-dd", Calendar.DATE, -1);
		String city=null;
		if (!filename.endsWith("_M.html")) {
			city = filename.substring(0, filename.lastIndexOf("."));
//			从mysql读数据
			Map<String, HomeHeatMap_PC> pv_uv_result = service.getCityData_PC_Month(strDate, city, "PC");
			Map<String, HomeHeatMap_PC> pv_uv_result_Y = new HashMap<String, HomeHeatMap_PC>();
			Map<String, HomeHeatMap_PC> pv_uv_result_today = service.getCityData_PC(strDate, city, "PC");
			//根据链接匹配数据
			html = change_PC(html,folder,city,pv_uv_result,pv_uv_result_Y,pv_uv_result_today);
		}
		return html;
	}

	/**
	 * 添加颜色区间bar
	 * @param date
	 * @param city
	 * @param html
	 * @param maxUV
	 * @return
	 */
	public static void addColorBar_PC(Document document,String date,String city,long[] cutPoints){
		//添加label，指向该城市M端的链接
//		String buttonBar = "<div align=\"center\">\n<br/>\n<button type=\"button\">\n"
//			+ " <a href=\"/heatmap/getPage?selectpvtype=m&selectdate="+date+"&selectedcityname="+city+"\" target=\"_self\">切换到m端</a>\n" + "</button>\n</div>";
		String replacedColorBar = colorBar.replace("#1#", String.valueOf(cutPoints[0]));
		replacedColorBar = replacedColorBar.replace("#2#", String.valueOf(cutPoints[1]));
		replacedColorBar = replacedColorBar.replace("#3#", String.valueOf(cutPoints[2]));
		replacedColorBar = replacedColorBar.replace("#4#", String.valueOf(cutPoints[3]));
		Element masthead = document.select("div[id=header]").first();
		masthead.prepend(replacedColorBar);
	}
		

	public static String change_PC( String html, String date, String city, Map<String, HomeHeatMap_PC> pv_uv_result,Map<String, HomeHeatMap_PC> pv_uv_result_Y,Map<String, HomeHeatMap_PC> pv_uv_result_today){
		Document document = Jsoup.parse(html);
		Elements links = document.getElementsByTag("a");
		//平均值
		long avgPV = getAVG(pv_uv_result_today);
		//切点
		long[] cutPoints = getCutPoint(avgPV);
		for(Element link : links) {
			String linkHref = formatHref(link.attr("href"));
			String linkText = getString(link.text(), "-");
			String tongji_tag = getString(link.attr("tongji_tag"), "-");
			String key  = StringUtils.join(new String[]{linkHref,linkText,tongji_tag},"_");
			HomeHeatMap_PC pv_uv_data = pv_uv_result.get(key);
			HomeHeatMap_PC pv_uv_data_Y=pv_uv_result_Y.get(key);
			int pvCount = 0;
			if (pv_uv_data != null) {
				pvCount = pv_uv_data.getClick_pv();
			}else{
				pv_uv_data = new HomeHeatMap_PC();
			}
			if(pv_uv_data_Y == null){
				pv_uv_data_Y = new HomeHeatMap_PC();
			}
			String color = "";
			
			if (pvCount < cutPoints[0])
				color = "#e1e1e1";
			else if (pvCount < cutPoints[1])
				color = "#ffd985";
			else if (pvCount < cutPoints[2])
				color = "#ffa037";
			else if (pvCount < cutPoints[3])
				color = "#ff5f3d";
			else
				color = "#be0100";
			String toolTip = getToolTip(pv_uv_data, pv_uv_data_Y);
			link.attr("title", toolTip);
			String style = changeBGColor(link.attr("style"), color);
			link.attr("style", style);
		}
		addColorBar_PC(document, date, city, cutPoints);
		html = document.html().replace("\n  ﻿   \n", "\n");
		
		return changeImgPath(html,date);
	}
	
	/**
	 * 设置提示框
	 */
	public static String getToolTip(HomeHeatMap_PC pv_uv_data, HomeHeatMap_PC pv_uv_data_Y){
		String tip =  "点击量: " + pv_uv_data.getClick_pv() 
		+ "\n点击人数: "  + pv_uv_data.getClick_uv() 
		+ "\n后续转化:\n详情页PV: " + pv_uv_data.getAll_vppv()
		+ "\n详情页UV: " + pv_uv_data.getAll_vpuv();
		return tip;
	}
	
	
	/**
	 * 更改背景色
	 * @return
	 */
	public static String changeBGColor(String oldStyle, String color) {
		if(StringUtils.isBlank(oldStyle)){
			return "background-color:" + color;
		}else{
			return "background-color:" + color+ "; "+oldStyle;
		}
	}

	/**
	 * 更改图片路径
	 * @param html
	 * @param date
	 * @return
	 */
	public static String changeImgPath(String html, String date) {
		StringBuffer sb = new StringBuffer();
		ArrayList<String> srcList = new ArrayList<String>();
		String srcReg = "http://([^<>'+()]*?)\\.(js|css|jpeg|jpg|png|gif|bmp|swf)";
		try {
			Pattern p = Pattern.compile(srcReg);
			Matcher m = p.matcher(html);
			while (m.find()) {
				String src = m.group();
				srcList.add(src);
				int i = src.indexOf("?");
				if (i != -1)
					src = src.substring(0, i);
				m.appendReplacement(sb,
						"/heatmap/" + date + "/"
								+ src.substring(src.lastIndexOf("/") + 1));
			}
			m.appendTail(sb);
		} catch (Exception e) {
			e.printStackTrace();
			return html;
		}
		return sb.toString();
	}

	private static String formatHref(String href){
		String result = "";
		if(StringUtils.isNotBlank(href)){
			String url = href.split("\\?")[0];
			String patternString = "http://[^/]*|https://[^/]*";
			Pattern pattern = Pattern.compile(patternString); 
		    Matcher matcher = pattern.matcher(url); 
		    
		    if(matcher.find()){
		    	String urltmp = url.replace(matcher.group(), "");
		    	if(StringUtils.isBlank(urltmp)){ // 去掉域名后 空  用去参的href代替
					result = url;
		    	}else{	// 获取相对路径				
					result = urltmp;
		    	}
		    }else{ // href 不以http://开头
		    	result = url;
		    }
			
		    if("/".equals(result)){// 最后如果处理后只剩 / 还原到去参后
		    	result = url;
		    }
		    
		}else{ // href 空
			return "";
		}
		if(!result.startsWith("http") && !result.startsWith("/")){
			result = "/"+result;
		}
		return result;
	}
	
	public static String getString(String text, String defaultVal) {
		if(StringUtils.isBlank(text)){
			text = defaultVal;
		}
		return text;
	}
	
	public static long getAVG(Map<String, HomeHeatMap_PC> pv_uv_result){
		long totalPV = 0;
		for(HomeHeatMap_PC vo : pv_uv_result.values()){
			totalPV += vo.getClick_pv();
		}
		
		if(pv_uv_result.values().size()  > 0)
			return totalPV/pv_uv_result.values().size();
		return 1;
	}
	
	public static long[] getCutPoint(long avg){
		long p1 = (long)(avg*0.6);
		long p2 = (long)(avg*1.8);
		long p3 = (long)(avg*3);
		long p4 = (long)(avg*6);
		if(avg >= 167){
			return new long[]{p1/100*100,p2/100*100,p3/100*100,p4/100*100};
		}else if(avg <=17){
			return new long[]{p1,p2,p3,p4};
		}else{
			return new long[]{p1/10*10,p2/10*10,p3/10*10,p4/10*10};
		}
	}
}
